package com.example.analysis.utils;

import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.stat.descriptive.moment.Mean;
import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation;

public class PCAUtils {
    public static RealMatrix standardize(RealMatrix data) {
        int numRows = data.getRowDimension();
        int numCols = data.getColumnDimension();

        // 存储均值和标准差
        double[] means = new double[numCols];
        double[] stdDevs = new double[numCols];

        // 计算每列的均值和标准差
        Mean meanCalculator = new Mean();
        StandardDeviation stdDevCalculator = new StandardDeviation();
        for (int col = 0; col < numCols; col++) {
            double[] columnData = data.getColumn(col);
            means[col] = meanCalculator.evaluate(columnData);
            stdDevs[col] = stdDevCalculator.evaluate(columnData);
        }

        // 创建标准化后的矩阵
        RealMatrix standardized = data.copy();
        for (int col = 0; col < numCols; col++) {
            double mean = means[col];
            double stdDev = stdDevs[col] == 0 ? 1.0 : stdDevs[col]; // 避免除以0
            for (int row = 0; row < numRows; row++) {
                double value = standardized.getEntry(row, col);
                standardized.setEntry(row, col, (value - mean) / stdDev);
            }
        }

        return standardized;
    }
}
